package com.weedsdream.function

import android.widget.Toast
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxScope
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableFloatStateOf
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.weedsdream.BaseActivity
import com.weedsdream.compose.HLine
import com.weedsdream.compose.Space
import kotlinx.coroutines.delay

/**Android系统原弹窗*/
fun toast(str: String, length: Int = Toast.LENGTH_SHORT) {
    Toast.makeText(BaseActivity.activity, str, length).show()
}

/**自定义Compose弹窗组件-请在必要的地方加载Toast组件
 * @param nString 内容字符串,如果为null则无提示内容
 * @param nTitle 标题字符串
 * @param autoClose 在指定时间后自动关闭，如果为null则不会自动关闭
 * @param nBtnList 当autoClose==null，如果不为空则会创建交互按钮
 * @param nMustChose 当autoClose==null时，如果为true，则nBtnList不可为空(如果为空则使用默认按钮)，用户必须点击某个按钮才能关闭弹窗
 * @param nContent 子Ui，注意不要使用fillMaxHeight,因为上下文是LazyColumn!*/
fun toast(
    nString: String? = null,
    nTitle: String = "提示",
    autoClose: Long? = 1000,
    nBtnList: List<ToastBtn>? = null,
    nMustChose: Boolean = false,
    nContent: @Composable (BoxScope.() -> Unit)? = null
) {
    string = nString
    title = nTitle
    alpha = 1f
    btnList.clear()
    if (autoClose == null) btnList.apply {
        needBtn = true
        mustChose = nMustChose
        if (nBtnList == null) {
            if (nMustChose) addAll(listOf(ToastBtn.cancel(), ToastBtn.ensure()))
        } else addAll(nBtnList)
    } else inCoroutine {//显示时间后自动关闭弹窗
        var l = (autoClose * 0.7).toLong()//完全显示周期
        delay(l)
        l = (autoClose - l) / 10//剩余显示时间分10次逐渐消失
        while (toastOpen) {
            delay(l)
            alpha -= 0.1f
            if (alpha <= 0f) toastOpen = false
        }
    }
    content = nContent
    toastOpen = true
}

/**弹窗开启状态*/
private var toastOpen by mutableStateOf(false)

/**是否需要提供触摸交互*/
private var needBtn by mutableStateOf(true)

/**标题*/
private var title by mutableStateOf("提示")

/**内容字符串*/
private var string by mutableStateOf<String?>(null)

/**透明度*/
private var alpha by mutableFloatStateOf(1f)

/**按钮组*/
private val btnList = mutableStateListOf(ToastBtn.cancel(), ToastBtn.ensure())

/**强制点击按钮，true时背景蒙版拦截触摸并且不可操作，否则可通过背景蒙版关闭弹窗*/
private var mustChose by mutableStateOf(false)

/**指定嵌套Compose*/
private var content by mutableStateOf<@Composable (BoxScope.() -> Unit)?>(null)

/**弹窗组件*/
@Preview(widthDp = 600, heightDp = 350)
@Composable
fun Toast(test: Boolean = true) {
    if (test || toastOpen) Box(
        Modifier
            .fillMaxSize()
            .alpha(alpha)
            .pointerInput(Unit) {
                detectTapGestures {
                    if (!mustChose) toastOpen = false
                }
            }) {
        Space(Color.DarkGray)
        Box(
            Modifier
                .fillMaxSize(0.7f)
                .align(Alignment.Center)
                .border(1.dp, Color.DarkGray)
        ) {
            Space(Color.Cyan, 0.5f) {}
            Column {
                //标题
                Box(Modifier.fillMaxWidth()) {
                    Text(
                        text = title, fontSize = 14.sp,
                        modifier = Modifier
                            .padding(8.dp)
                            .align(Alignment.Center)
                    )
                }
                HLine()
                //内容
                LazyColumn(
                    Modifier
                        .padding(8.dp)
                        .fillMaxWidth()
                        .weight(1f)
                ) {
                    if (string != null) item {
                        Text(text = string ?: "", fontSize = 13.sp)
                    }
                    if (content != null) item {
                        Box(Modifier.padding(5.dp)) {
                            if (content != null) content!!()
                        }
                    }
                }
                //按钮组
                if (needBtn && btnList.isNotEmpty()) {
                    HLine()
                    Row(Modifier.fillMaxWidth()) {
                        //分割竖线
                        var height by remember { mutableIntStateOf(0) }
                        Text(text = "按钮", fontSize = 14.sp, maxLines = 1,
                            modifier = Modifier
                                .width(0.dp)
                                .onGloballyPositioned {
                                    height = it.size.height
                                })
                        val vLine = @Composable {
                            Spacer(
                                Modifier
                                    .height(with(LocalDensity.current) { height.toDp() })
                                    .width(1.dp)
                                    .background(Color.DarkGray)
                                    .align(Alignment.CenterVertically)
                            )
                        }
                        //所有按钮
                        for (btn in btnList) {
                            if (btn != btnList.first()) vLine()
                            Box(
                                Modifier
                                    .weight(1f)
                                    .clickable { toastOpen = !btn.click() }
                                    .padding(vertical = 5.dp)) {
                                Text(
                                    text = btn.tag, color = btn.color.value, fontSize = 14.sp,
                                    modifier = Modifier.align(Alignment.Center)
                                )
                            }
                        }
                    }
                }
            }
        }
    }
}

/**弹窗提供的按钮
 * @property tag 按钮名
 * @property color 按钮色
 * @property click 点击行为.返回true则关闭弹窗*/
data class ToastBtn(
    val tag: String,
    val color: MutableState<Color> = mutableStateOf(Color.Black),
    val click: () -> Boolean = { true }
) {
    companion object {
        /**取消按钮预设*/
        fun cancel(click: () -> Boolean = { true }) =
            ToastBtn("取消", mutableStateOf(Color.DarkGray)) { click() }

        /**确定按钮预设*/
        fun ensure(click: () -> Boolean = { true }) =
            ToastBtn("确定", mutableStateOf(Color.Black)) { click() }
    }
}
